from flask import Blueprint, request

from app.utils import response, response_get
from app import db
from app.models import Model
moxing_bp = Blueprint('moxing1', __name__)


@moxing_bp.route('/upload_model', methods=['POST'])
def create_model():
    user_id = request.args.get('user_id')
    model_name = request.args.get('model_name')
    model_type = request.args.get('model_type')
    model_describe = request.args.get('model_describe')
    model_protect = request.args.get('model_protect')
    print(user_id,model_name, model_type, model_describe, model_protect)
    # if not all([user_id, model_name, model_type]):
    #     return response(400)
    print(0)
    new_model = Model(
        user_id=user_id,
        model_name=model_name,
        model_type=model_type,
        model_describe=model_describe,
        model_protect=model_protect,
    )
    print(1)
    db.session.add(new_model)
    db.session.commit()
    print(3)
    return response(200)


@moxing_bp.route('/got_model_manage', methods=['GET'])
def get_models():
    user_id = request.args.get('user_id')
    limit = int(request.args.get('limit', 10))
    page = int(request.args.get('page', 1))
    sort_by = request.args.get('sort_by', 'model_name')
    sorting_order = request.args.get('sorting_order', 'desc')
    status = request.args.get('status', 'all')
    search = request.args.get('search', '')

    query = Model.query.filter(Model.user_id == user_id)

    if status != 'all':
        query = query.filter_by(model_state=status)

    if search:
        query = query.filter(Model.model_name.contains(search))

    if sorting_order == 'asc':
        query = query.order_by(getattr(Model, sort_by).asc())
    else:
        query = query.order_by(getattr(Model, sort_by).desc())

    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    models = pagination.items

    data = [{
        'model_id': model.model_id,
        'model_name': model.model_name,
        'model_type': model.model_type,
        'model_describe': model.model_describe,
        'model_protect': model.model_protect,
    } for model in models]

    response_data = {
        'code': 200,
        'data': data,
        'pagination': {
            'page': page,
            'perpage': limit,
            'total': pagination.total
        }
    }
    return response_get(200, response_data)
